package com.lagou.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lagou.pojo.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.cglib.reflect.FastClass;
import org.springframework.cglib.reflect.FastMethod;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;

@Service
public class UserServiceHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("into set applicationContext = [" + applicationContext + "]");
        UserServiceHandler.applicationContext = applicationContext;
    }

    // 当客户端读取数据时, 该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws InvocationTargetException, ClassNotFoundException {
        // RpcRequest rpcRequest = (RpcRequest) msg;
        RpcRequest rpcRequest = JSONObject.parseObject(JSON.toJSONString(msg), RpcRequest.class);
        handler(rpcRequest);
        ctx.writeAndFlush("success");
    }

    private void handler(RpcRequest request) throws ClassNotFoundException, InvocationTargetException {
        // 使用Class.forName进行加载Class文件
        Class<?> clazz = Class.forName(request.getClassName());
        Object serviceBean = applicationContext.getBean(clazz);
        Class<?> serviceClass = serviceBean.getClass();
        String methodName = request.getMethodName();
        Class<?>[] parameterTypes = request.getParameterTypes();
        Object[] parameters = request.getParameters();
        FastClass fastClass = FastClass.create(serviceClass);
        FastMethod fastMethod = fastClass.getMethod(methodName, parameterTypes);
        fastMethod.invoke(serviceBean, parameters);
    }
}
